package com.jindreamit.m3u8.download.runnable;

import com.alibaba.fastjson.JSONObject;
import com.jindreamit.m3u8.download.jwt.LoginForJWT;
import com.jindreamit.m3u8.download.util.RedisUtils;
import com.jindreamit.m3u8.download.util.ThreadPoolUtils;
import org.jsoup.Jsoup;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;

public class ReadM3u8Runnable implements Runnable {

    static final public List<ReadM3u8Runnable> errorM3u8Runnable = new LinkedList<>();


    private String url;

    private String dirPath;

    public ReadM3u8Runnable(String url, String dirPath) {
        this.url = url;
        this.dirPath = dirPath;
    }

    @Override
    public void run() {
        try {
            List<String> lines = Arrays.asList(Jsoup.connect(this.url)
                    .ignoreContentType(true)
                    .get()
                    .body()
                    .text()
                    .split(" "));
            new File(this.dirPath + "/").mkdirs();
            File file = new File(this.dirPath + "/" + "index.m3u8");
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            for (int i = 0; i < lines.size(); i++) {
                String line = lines.get(i);
                if (line.contains("#EXT-X-KEY:METHOD=AES-128,URI=")) {
                    String url = line.split("#EXT-X-KEY:METHOD=AES-128,URI=")[1].replaceAll("\"", "");
//                    System.out.println(url);
                    ThreadPoolUtils.execute(new DownloadRunnable(this.dirPath, url, "key.key"));
                    line = "#EXT-X-KEY:METHOD=AES-128,URI=\"key.key\"";
                    writer.write(line);
                    writer.newLine();
                } else if (line.toCharArray()[0] != '#') {
                    String name = line.split("/")[line.split("/").length - 1];
                    ThreadPoolUtils.execute(new DownloadRunnable(this.dirPath, line, name));
                    writer.write(name);
                    if (i != lines.size() - 1) {
                        writer.newLine();
                    }
                } else {
                    writer.write(line);
                    writer.newLine();
                }
            }
            writer.flush();
            writer.close();
            System.out.println(lines);
        } catch (Exception e) {
            e.printStackTrace();
            errorM3u8Runnable.add(this);
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        RedisUtils.append("error_m3u8", JSONObject.parseObject(errorM3u8Runnable.toString()).toJSONString());
    }
}
